import gdata.auth
import gdata.analytics.service
import datetime
import re

# comment the next two lines before uploading (they are for testing on SDK with python 2.6)
#import logging 
#logging.logMultiprocessing = 0

yesterday=datetime.date.today()-datetime.timedelta(days=1)
difference = datetime.timedelta(weeks=-4)
before=yesterday+difference

client = gdata.analytics.service.AnalyticsDataService()
client.ClientLogin('yourmail@gmail.com', 'password')
feed = client.GetData(ids='ga:20437395',
                  dimensions='ga:pagePath,ga:pageTitle',
                  metrics='ga:pageviews',
                  sort='-ga:pageviews',
                  start_date=before.isoformat(),
                  end_date=yesterday.isoformat(),
                  max_results=50,
                  start_index=1)

visited=[]
for entry in feed.entry:
  if str(entry.pageTitle) != '(not set)' and str(entry.pagePath) != '/' and str(entry.pagePath)[0:6] != '/html?':
    visited.append((entry.pagePath.value,entry.pageTitle.value,entry.pageviews.value))


# ten most popular posts
for post in visited[0:10]:
  print('document.write(\'<li>\');')
  print('document.write(\'<a href="' + post[0] + '">\');')
  print('document.write(\'' + re.escape(post[1]) + '</a>\');')
  print('document.write(\'</li>\');')

